import requests
from bs4 import BeautifulSoup
import json
import csv

url = "http://data.sports.sohu.com/nba/nba_players_rank.php?order_by=points&spm=smpc.fb-nba-home.top-dc.2.1620824904040nf6byr7"

res = requests.get(url)
res.encoding = 'utf-8'

soup = BeautifulSoup(res.text, 'html.parser')

data = []
for tr in soup.select('table.rank-table > tbody > tr'):
    player_data = {}
    tds = tr.select('td')
    player_data['ranking'] = tds[0].get_text()
    player_data['name'] = tds[1].get_text()
    player_data['team'] = tds[2].get_text()
    player_data['points'] = tds[3].get_text()
    player_data['rebounds'] = tds[4].get_text()
    player_data['assists'] = tds[5].get_text()
    data.append(player_data)

# 将数据写入JSON文件
with open('nba_data.json', 'w') as f:
    json.dump(data, f, ensure_ascii=False)

# 将数据写入CSV文件
with open('nba_data.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['排名', '球员', '球队', '得分', '篮板', '助攻'])
    for player_data in data:
        writer.writerow([player_data['ranking'], player_data['name'], player_data['team'], player_data['points'], player_data['rebounds'], player_data['assists']])
